<template>
  <div class="vehicle-container">
	  <el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
	          <el-col :span="24" class="text-center">
	              <div class="title-wrapper">
	              <i class="el-icon-search el-icon--large"></i>
	              <h1 class="main-title">车辆占道信息管理系统</h1>
	              <p class="sub-title">细致追踪车辆占道信息，及时联动处置违规行为，每一次严谨管理，都是为了保障道路秩序与出行安全</p>
	              </div>
	          </el-col>
	      </el-row>
    <!-- 详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="车辆信息详情"
      width="70%"
      destroy-on-close
    >
      <el-descriptions title="车辆详细信息" direction="vertical" :column="4" :model="currentVehicle" border>
        <el-descriptions-item label="车辆ID" :span="2">{{ currentVehicle.id }}</el-descriptions-item>
        <el-descriptions-item label="车牌号" :span="2">{{ currentVehicle.licensePlate }}</el-descriptions-item>
        <el-descriptions-item label="居民ID" :span="2">{{ currentVehicle.residentId }}</el-descriptions-item>
        <el-descriptions-item label="居民姓名" :span="2">{{ currentVehicle.name }}</el-descriptions-item>
        <el-descriptions-item label="联系方式" :span="4">{{ currentVehicle.contactInfo }}</el-descriptions-item>
        <el-descriptions-item label="注册照片" :span="4">
          <el-image 
            v-if="currentVehicle.registrationPhoto" 
            :src="getImageUrl(currentVehicle.registrationPhoto)" 
            style="width: 300px; height: auto" 
            :preview-src-list="[getImageUrl(currentVehicle.registrationPhoto)]"
          ></el-image>
          <span v-else>无照片</span>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>


    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑车辆信息"
      width="60%"
      destroy-on-close
    >
      <el-form 
        :model="editForm" 
        :rules="rules" 
        ref="editFormRef" 
        label-width="120px" 
        class="demo-ruleForm"
      >
        <el-form-item label="车辆ID" prop="id" disabled>
          <el-input v-model="editForm.id"></el-input>
        </el-form-item>
        <el-form-item label="车牌号" prop="licensePlate">
          <el-input v-model="editForm.licensePlate"></el-input>
        </el-form-item>
        <el-form-item label="居民ID" prop="residentId">
          <el-input v-model.number="editForm.residentId" type="number"></el-input>
        </el-form-item>
        <el-form-item label="注册照片">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-change="handleEditImageChange"
            accept="image/*"
          >
            <img v-if="editImageUrl" :src="editImageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div style="margin-top: 10px; font-size: 12px; color: #606266;">
            提示：点击上传新照片，不修改请保持不变
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
          <el-button @click="editDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <!-- 新增对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增车辆信息"
      width="60%"
      destroy-on-close
    >
      <el-form 
        :model="addForm" 
        :rules="rules" 
        ref="addFormRef" 
        label-width="120px"
      >
        <el-form-item label="车牌号" prop="licensePlate">
          <el-input v-model="addForm.licensePlate" placeholder="例如: 京A12345"></el-input>
        </el-form-item>
        <el-form-item label="居民ID" prop="residentId">
          <el-input v-model.number="addForm.residentId" type="number" placeholder="请输入居民ID"></el-input>
        </el-form-item>
        <el-form-item label="注册照片">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-change="handleAddImageChange"
            accept="image/*"
          >
            <img v-if="addImageUrl" :src="addImageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div style="margin-top: 10px; font-size: 12px; color: #606266;">
            提示：照片为可选，可不上传
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAddForm">提交</el-button>
          <el-button @click="addDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <!-- 数据操作区 -->
    <el-row>
      <el-row :gutter="10" style="width: 100%; margin-bottom: 20px; align-items: center;">
        <el-col :span="6">
          <el-input 
            placeholder="输入车牌号进行查询" 
            v-model="searchLicensePlate" 
            style="width: 100%;"
            @keyup.enter="handleSearch"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-input 
            placeholder="输入居民ID进行查询" 
            v-model.number="searchResidentId" 
            type="number"
            style="width: 100%;"
          ></el-input>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="primary" 
            icon="el-icon-search" 
            @click="handleSearch" 
            style="width: 100%;"
          >
            搜索
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="success" 
            icon="el-icon-refresh" 
            @click="resetSearch" 
            style="width: 100%;"
          >
            重置
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="primary" 
            icon="el-icon-plus" 
            @click="openAddDialog" 
            style="width: 100%;"
          >
            新增
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="info" 
            icon="el-icon-user" 
            @click="showVehiclesByResident" 
            style="width: 100%;"
          >
            按居民查询
          </el-button>
        </el-col>
      </el-row>
      
      <!-- 表格部分 -->
      <el-table 
        :data="filteredData.slice((currentPage-1)*pageSize, currentPage*pageSize)" 
        border 
        style="width: 100%;"
        height="450"
      >
        <el-table-column prop="id" label="车辆ID" width="100" align="center"></el-table-column>
        <el-table-column prop="licensePlate" label="车牌号" width="120" align="center"></el-table-column>
        <el-table-column prop="residentId" label="居民ID" width="120" align="center"></el-table-column>
        <el-table-column prop="name" label="居民姓名" width="120" align="center"></el-table-column>
        <el-table-column prop="contactInfo" label="联系方式" width="150" align="center"></el-table-column>
        <el-table-column prop="hasPhoto" label="是否有照片" width="120" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.hasPhoto ? 'success' : 'info'">
              {{ scope.row.hasPhoto ? '有' : '无' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button type="primary" size="mini" icon="el-icon-view" @click="openDetailDialog(scope.row)">查看</el-button>
              <el-button type="warning" size="mini" icon="el-icon-edit" @click="openEditDialog(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteVehicle(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-row type="flex" justify="center" style="margin-top: 20px;">
        <el-pagination 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5,10,20,50]" 
          :page-size="pageSize" 
          :total="filteredData.length"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </el-row>
    </el-row>
  </div>
</template>


<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { post } from '../../utils/axios.js'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'


// 对话框状态
const dialogVisible = ref(false)
const editDialogVisible = ref(false)
const addDialogVisible = ref(false)


// 搜索条件
const searchLicensePlate = ref('')
const searchResidentId = ref('')


// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)


// 数据存储
const vehicleList = ref([])
const filteredData = ref([])


// 表单引用
const editFormRef = ref(null)
const addFormRef = ref(null)


// 图片处理相关
const addImageUrl = ref('')
const addImageFile = ref(null)
const editImageUrl = ref('')
const editImageFile = ref(null)


// 当前选中的车辆信息
const currentVehicle = reactive({
  id: null,
  licensePlate: '',
  registrationPhoto: null,
  residentId: null,
  name: '',
  contactInfo: '',
  hasPhoto: false
})


// 编辑表单数据
const editForm = reactive({
  id: null,
  licensePlate: '',
  residentId: null,
  registrationPhoto: null
})


// 新增表单数据
const addForm = reactive({
  licensePlate: '',
  residentId: null,
  registrationPhoto: null
})


// 表单验证规则
const rules = reactive({
  licensePlate: [
    { required: true, message: '请输入车牌号', trigger: 'blur' }
  ],
  residentId: [
    { required: true, message: '请输入居民ID', trigger: 'blur' },
    { type: 'number', message: '居民ID必须为数字', trigger: 'blur' }
  ]
})


// 处理新增图片上传
const handleAddImageChange = (file) => {
  addImageFile.value = file.raw
  addImageUrl.value = URL.createObjectURL(file.raw)
  // 转换为base64以便后续处理
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = (e) => {
    // 提取base64数据部分，去掉前缀
    addForm.registrationPhoto = e.target.result.split(',')[1]
  }
}


// 处理编辑图片上传
const handleEditImageChange = (file) => {
  editImageFile.value = file.raw
  editImageUrl.value = URL.createObjectURL(file.raw)
  // 转换为base64以便后续处理
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = (e) => {
    // 提取base64数据部分，去掉前缀
    editForm.registrationPhoto = e.target.result.split(',')[1]
  }
}


// 将字节数组转换为图片URL
const getImageUrl = (byteArray) => {
  if (!byteArray) return ''
  // 如果后端返回的是base64字符串
  if (typeof byteArray === 'string') {
    return `data:image/jpeg;base64,${byteArray}`
  }
  // 如果后端返回的是Uint8Array
  if (byteArray instanceof Uint8Array) {
    return URL.createObjectURL(new Blob([byteArray]))
  }
  return ''
}


// 打开详情对话框
function openDetailDialog(row) {
  dialogVisible.value = true
  Object.assign(currentVehicle, {
    ...row,
    hasPhoto: !!row.registrationPhoto
  })
}


// 打开编辑对话框
function openEditDialog(row) {
  editDialogVisible.value = true
  editImageUrl.value = row.registrationPhoto ? getImageUrl(row.registrationPhoto) : ''
  editImageFile.value = null
  Object.assign(editForm, {
    id: row.id,
    licensePlate: row.licensePlate,
    residentId: row.residentId,
    registrationPhoto: null // 初始不设置，只有上传新图片才会设置
  })
}


// 打开新增对话框
function openAddDialog() {
  addDialogVisible.value = true
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
  addForm.licensePlate = ''
  addForm.residentId = null
  addForm.registrationPhoto = null
  addImageUrl.value = ''
  addImageFile.value = null
}


// 提交编辑表单
function submitEditForm() {
  editFormRef.value.validate((valid) => {
    if (!valid) return;
    
    const loading = ElLoading.service({ text: '更新中...' })
    
    // 构建表单数据
    const formData = new FormData()
    formData.append('vehicleId', editForm.id)
    formData.append('licensePlate', editForm.licensePlate)
    formData.append('residentId', editForm.residentId)
    
    // 如果有新图片才添加
    if (editImageFile.value) {
      formData.append('registrationPhoto', editImageFile.value)
    }
    
    post('/sc/vehicles/updateVehicleInfo', formData, (res) => {
      loading.close()
      if (res.status === 1 || res.msg?.includes('成功')) {
        ElMessage.success('更新成功！')
        editDialogVisible.value = false
        fetchVehicleList()
      } else {
        ElMessage.error(res.msg || '更新失败')
      }
    }, {
      // 上传文件需要设置的请求头
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  })
}


// 提交新增表单
function submitAddForm() {
  addFormRef.value.validate((valid) => {
    if (!valid) return;
    
    const loading = ElLoading.service({ text: '添加中...' })
    
    // 构建表单数据
    const formData = new FormData()
    formData.append('licensePlate', addForm.licensePlate)
    formData.append('residentId', addForm.residentId)
    
    // 如果有图片才添加
    if (addImageFile.value) {
      formData.append('registrationPhoto', addImageFile.value)
    }
    
    post('/sc/vehicles/addVehicleInfo', formData, (res) => {
      loading.close()
      if (res.status === 1 || res.msg?.includes('成功')) {
        ElMessage.success('添加成功！')
        addDialogVisible.value = false
        fetchVehicleList()
      } else {
        ElMessage.error(res.msg || '添加失败')
      }
    }, {
      // 上传文件需要设置的请求头
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  })
}


// 删除车辆信息
function deleteVehicle(row) {
  ElMessageBox.confirm(`确定删除车辆 ${row.licensePlate} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const loading = ElLoading.service({ text: '删除中...' })
    const params = new URLSearchParams();
    params.append('vehicleId', row.id);
    
    post('/sc/vehicles/deleteVehicleInfo', params, (res) => {
      loading.close()
      if (res.status === 1 || res.msg?.includes('成功')) {
        ElMessage.success('删除成功！')
        fetchVehicleList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
  }).catch(() => {})
}


// 搜索处理
function handleSearch() {
  const loading = ElLoading.service({ text: '搜索中...' })
  
  if (searchResidentId.value) {
    // 按居民ID搜索
    const params = new URLSearchParams();
    params.append('residentId', searchResidentId.value);
    
    post('/sc/vehicles/getLicenseByResidentId', params, (res) => {
      loading.close()
      if (res.status === 1 && res.data) {
        // 如果返回的是车牌号列表，我们需要从本地数据中过滤
        const licensePlates = res.data;
        filteredData.value = vehicleList.value.filter(item => 
          licensePlates.includes(item.licensePlate)
        );
      } else {
        filteredData.value = []
      }
      showSearchResultMessage()
    })
  } else if (searchLicensePlate.value) {
    // 按车牌号搜索，本地过滤
    filteredData.value = vehicleList.value.filter(item => 
      item.licensePlate.includes(searchLicensePlate.value)
    )
    loading.close()
    showSearchResultMessage()
  } else {
    // 显示全部
    filteredData.value = [...vehicleList.value]
    loading.close()
    showSearchResultMessage()
  }
  
  currentPage.value = 1 // 重置到第一页
}


// 按居民查询车辆
function showVehiclesByResident() {
  if (!searchResidentId.value) {
    ElMessage.warning('请输入居民ID')
    return
  }
  handleSearch()
}


// 显示搜索结果消息
function showSearchResultMessage() {
  if (filteredData.value.length > 0) {
    ElMessage.success(`找到 ${filteredData.value.length} 条记录`)
  } else {
    ElMessage.warning('未找到匹配记录')
  }
}


// 重置搜索
function resetSearch() {
  searchLicensePlate.value = ''
  searchResidentId.value = ''
  filteredData.value = [...vehicleList.value]
  currentPage.value = 1
}


// 分页大小变化
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1
}


// 当前页变化
function handleCurrentChange(val) {
  currentPage.value = val
}


// 获取所有车辆信息
function fetchVehicleList() {
  const loading = ElLoading.service({ text: '加载中...' })
  post('/sc/vehicles/getAllVehicleInfo', {}, (res) => {
    loading.close()
    if (res.status === 1 && res.data) {
      // 处理车辆数据，添加hasPhoto属性
      vehicleList.value = res.data.map(vehicle => ({
        ...vehicle,
        hasPhoto: !!vehicle.registrationPhoto
      }))
      filteredData.value = [...vehicleList.value]
    } else {
      ElMessage.error(res.msg || '获取数据失败')
      vehicleList.value = []
      filteredData.value = []
    }
  })
}


// 页面加载时获取数据
onMounted(() => {
  fetchVehicleList()
})
</script>


<style scoped>
.vehicle-container {
  width: auto;
  padding: 20px;
}

/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}

.operation-buttons {
  display: flex;
  gap: 4px;
}


.operation-buttons .el-button--mini {
  padding: 1px 6px;
  font-size: 12px;
  height: 24px;
  min-width: auto;
}


.el-table {
  margin-top: 20px;
}


.el-pagination {
  margin-top: 20px;
}


.el-form-item .el-button,
.el-col .el-button {
  margin-right: 5px;
}


.el-form {
  padding: 10px;
}

/* 图片上传样式 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
